package com.foreveross.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.foreveross.common.CommonUtil;
import com.foreveross.common.Constants;
import com.foreveross.common.Exception.ExceptionConstant;
import com.foreveross.vo.common.ResultVo;

public class FileUtil {

	private static Logger log = Logger.getLogger(FileUtil.class);

	private static List fileTypeList = Arrays.asList("jpg", "jpeg", "gif",
			"ai", "pdg", "bmp", "png");

	public static final String fileRoot = "/fileupload/";

	private static List<String> fileUrl = new ArrayList<String>();

	public static String formatDate(Date date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(date);
	}

	/**
	 * 上传多文件 spring调用参数设置：@RequestParam("files") MultipartFile[] files
	 * html多文件格式：xxx:<input type="file" name="files"> hhh:<input type="file"
	 * name="files">
	 * 
	 * @param request
	 * @param files
	 * @param uploadPath
	 * @param isImg
	 * @return
	 */
	public static List<ResultVo> uploadFileMulti(HttpServletRequest request,
			MultipartFile[] files, String uploadPath, boolean isImg) {
		List<ResultVo> list = new ArrayList<ResultVo>();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				ResultVo resultVo = uploadFile(request, file, uploadPath, isImg);
				list.add(resultVo);
			}
		}
		return list;
	}

	/**
	 * 文件上传
	 * 
	 * @param request
	 * @param uploadPath
	 * @param isImg
	 * @return
	 */
	public static ResultVo uploadFile(HttpServletRequest request,
			MultipartFile file, String uploadPath, boolean isImg) {
		// 验证文件
		ResultVo resultVo = validateFile(file, isImg);
		if (resultVo.isSuccess()) {
			// 上传文件
			resultVo = uploadFile(file, CommonUtil.getRealPath(request), fileRoot+uploadPath);
		}
		return resultVo;
	}

	/**
	 * 文件下载
	 * 
	 * @param path
	 * @param response
	 */
	public static void downLoadFile(String path, HttpServletResponse response) {
		try {
			File file = new File(path);
			String filename = file.getName();
			String ext = filename.substring(filename.lastIndexOf(".") + 1)
					.toUpperCase();
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(
					response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private static ResultVo validateFile(MultipartFile file, boolean isImg) {
		ResultVo resultVo = new ResultVo();
		resultVo.setSuccess(true);
		if (file.isEmpty()) {
			resultVo.setSuccess(false);
			resultVo.setMessage(ExceptionConstant.FILE_EMPTY_EX);
			return resultVo;
		}

		String uploadfileName = file.getOriginalFilename();
		String suffix = uploadfileName.substring(
				uploadfileName.lastIndexOf(".") + 1, uploadfileName.length());
		long size = file.getSize();
		if (isImg && !fileTypeList.contains(suffix.toLowerCase())) {
			resultVo.setSuccess(false);
			resultVo.setMessage(ExceptionConstant.FILE_TYPE_EX);
		} else if (isImg && size > Constants.IMG_MAX_SIZE) {
			resultVo.setSuccess(false);
			resultVo.setMessage(ExceptionConstant.FILE_IMA_SIZE_EX);
		} else if (!isImg && size > Constants.FILE_MAX_SIZE) {
			resultVo.setSuccess(false);
			resultVo.setMessage(ExceptionConstant.FILE_SIZE_EX);
		}
		return resultVo;
	}

	private static ResultVo uploadFile(MultipartFile file, String basePath,
			String uploadPath) {
		ResultVo resultVo = new ResultVo();

		String dbfilePath = "";
		try {
			String dateStr = "";
			String fileName = file.getOriginalFilename();
			System.out.println(fileName);

		    //转义拆分重命名文件
		    String[] strArr=fileName.split("\\.");
		    
			dateStr = formatDate(new Date());
			dbfilePath = uploadPath + dateStr + "_"
					+ CommonUtil.getRandomString(6)+"."+strArr[1];
			
			File uploadFile = new File(basePath + dbfilePath);
	        // 创建目录  
	        if (!uploadFile.exists()) {  
	        	uploadFile.getParentFile().mkdirs();// 目录不存在的情况下，创建目录。  
	        }  
			file.transferTo(uploadFile);
			resultVo.setSuccess(true);
			resultVo.setData(dbfilePath);
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage(ExceptionConstant.FILE_UPLOAD_EX);
		}
		return resultVo;
	}

	/**
	 * 删除 指定未指定的路径的文件
	 * @param fileUrls 指定的文件路径地址
	 */
	public static void deleteFiles(List<String> fileUrls) {
		try{
			//获取文件根路径下的所有文件地址
			List<String> fileAllUrl = getFiles(Constants.REAL_PATH+fileRoot,new ArrayList<String> ());
			//获取所有删除的文件地址
			List<String> deleteFileUrls = getDeleteFileUrls(fileAllUrl, fileUrls);
			
			for(String url : deleteFileUrls){
				deleteFile(url);
			}
		}catch(Exception e){
			e.printStackTrace();
			log.info("删除文件失败");
		}
		
	}
	
	/**
	 * 获取所有删除的文件地址
	 * @param allFileUrls
	 * @param fileUrls
	 * @return
	 */
	private static List<String> getDeleteFileUrls(List<String> allFileUrls,List<String> fileUrls){
		List<String> deleteFileUrls = new ArrayList<String>();
		System.out.println(fileUrls.get(0));
		for(String fileUrl : allFileUrls){
			if(!fileUrls.contains(fileUrl)){
				System.out.println("deleteFileUrl："+fileUrl);
				log.info("deleteFileUrl："+fileUrl);
				deleteFileUrls.add(fileUrl);
			}
		}
		for(String fileUrl :fileUrls){
			System.out.println("allFileUrl："+fileUrl);
			log.info("allFileUrl："+fileUrl);
		}
		return deleteFileUrls;
	}

	/**
	 * 通过递归得到某一路径下所有的目录及其文件
	 */
	public static List<String> getFiles(String filePath,List<String> fileAllUrl) {
		File root = new File(filePath);
		File[] files = root.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				/*
				 * 递归调用
				 */
				getFiles(file.getAbsolutePath(),fileAllUrl);
				
/*				System.out.println("显示" + filePath + "下所有子目录及其文件:"
						+ file.getAbsolutePath());*/
			} else {
				fileAllUrl.add(file.getAbsolutePath());
/*				System.out.println("显示" + filePath + "下所有子目录:"
						+ file.getAbsolutePath());*/
			}
		}
		return fileAllUrl;
	}
	
	/**
	 * 删除文件
	 * @param url
	 */
	public static void deleteFile(String url){
		File file = new File(url);
		if(file.exists()) file.delete();
	}

	/**
	 * 验证文件是否存在
	 * 
	 * @param fileLocation
	 * @return
	 */
	public static boolean isExistsFile(String fileLocation) {
		File file = new File(fileLocation);
		return file.exists();
	}
	
	public static List<String> getFileUrl(){
		List<String> fileUrl = new ArrayList<String>();
		fileUrl.add("E:\\apache-tomcat-6.0.35\\webapps\\HRTenement\\fileupload\\newdisk\\newsite_pic1.jpg");
		fileUrl.add("E:\\apache-tomcat-6.0.35\\webapps\\HRTenement\\fileupload\\push\\news_pic1.jpg");
		fileUrl.add("E:\\apache-tomcat-6.0.35\\webapps\\HRTenement\\fileupload\\push\\news_pic2.jpg");
		return fileUrl;
	}
	
	public static String getSuffix(String contentType){
		String expandedName = null;
		if (contentType.equals("image/pjpeg")
				|| contentType.equals("image/jpeg")) {
			// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
			expandedName = ".jpg";
		} else if (contentType.equals("image/png")
				|| contentType.equals("image/x-png")) {
			// IE6上传的png图片的headimageContentType是"image/x-png"
			expandedName = ".png";
		} else if (contentType.equals("image/gif")) {
			expandedName = ".gif";
		} else if (contentType.equals("image/bmp")) {
			expandedName = ".bmp";
		}
		return expandedName;
	}
	
	
	
	
	public static void main(String [] args) throws UnsupportedEncodingException{  
        String filePath = "d:/中基本原则/test2/tes基本原则.jsp";  
        System.out.println(new String(filePath.getBytes()));
/*        File fp = new File(filePath);  
        // 创建目录  
        if (!fp.exists()) {  
            fp.getParentFile().mkdirs();// 目录不存在的情况下，创建目录。  
        }  
        System.out.println("执行结束"+filePath);  */
    } 
}
